package com.example.sprintbootarithmetic.arithmeic;

import java.util.Arrays;

public class FinbonacciSearch {
    public static int maxsize = 100;

    public static void main(String[] args) {
        int[] arr = {1, 8, 10, 89, 1000, 1234};
        System.out.println("index=" + fibSearch(arr, 10));
    }

    public static int[] fib() {
        int[] max = new int[maxsize];
        max[0] = 1;
        max[1] = 1;
        for (int i = 2; i < maxsize; i++) {
            max[i] = max[i - 1] + max[i - 2];
        }
        return max;
    }

    public static int fibSearch(int[] a, int key) {
        int low = 0;
        int hign = a.length - 1;
        int k = 0;
        int mid = 0;
        int f[] = fib();
        while (hign > f[k - 1]) {
            k++;
        }
        int[] temp = Arrays.copyOf(a, f[k]);
        for (int i = hign + 1; i < temp.length; i++) {
            temp[i] = a[hign];
        }
        while (low <= hign) {
            mid = low + f[k - 1] - 1;
            if (key < temp[mid]) {
                hign = mid - 1;
                k--;
            } else if (key > temp[mid]) {//我们应该向数组的后面（右边）查找
                low = mid + 1;
                //为什么是k-2
                k -= 2;
            } else {
                if (mid <= hign) {
                    return mid;
                } else {
                    return hign;
                }
            }
        }
        return -1;
    }
}
